package com.qf.api.sys.mybatis.page;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.qf.core.response.ResponseResult;
import com.qf.core.utils.ServletUtils;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * @Author: sin
 * @Date: 2025/5/8 16:52
 * @Description: 分页处理控制层
 **/
@RestController
public class BaseController {
    /* 当前记录起始索引 */
    public static final String PAGE_NUM = "currentPage";

    /* 每页显示记录数 */
    public static final String PAGE_SIZE = "pageSize";

    /**
     * 封装分页数据
     */
    public static PageDTO getPageDto() {
        return new PageDTO(ServletUtils.getParameterToInt(PAGE_NUM), ServletUtils.getParameterToInt(PAGE_SIZE));
    }

    /**
     * 封装PageHelp的startPage方法
     */
    protected void startPage() {
        PageDTO PageDto = getPageDto();
        Integer pageNum = PageDto.getCurrentPage();
        Integer pageSize = PageDto.getPageSize();

        if (pageNum == null || pageNum <= 0) pageNum = 1;
        if (pageSize == null || pageSize <= 0) pageSize = 10;

        PageHelper.startPage(pageNum, pageSize);
    }

    /**
     * 响应分页数据
     */
    protected <T> PageResult<T> getData(List<T> list) {
        PageInfo<T> pageInfo = new PageInfo<>(list);
        return new PageResult<T>(pageInfo.getTotal(),list);
    }

    public static <T, R> PageResult<R> getData(List<T> list, Function<T, R> mapper) {
        PageInfo<T> pageInfo = new PageInfo<>(list);
        List<R> records = list.stream()
            .map(mapper)
            .collect(Collectors.toList());

        return new PageResult<R>()
            .setList(records)
            .setTotal(pageInfo.getTotal());
    }

    /**
     * 响应返回结果
     * 针对增删改操作  判断rows
     */
    protected ResponseResult<Boolean> isOk(boolean result){
        return result ? ResponseResult.success(true) : ResponseResult.fail("操作失败");
    }
}
